package com.fingard.dsp.bank.directbank.bob11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;

/**
 * BOB11-北京银行银保通
 */
public class BOB11BatPayRec extends BOB11Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    /**
     * 批量代收付提交
     *
     * @param p_reqBat 批量代收付请求对象
     * @return 批量代收付响应对象
     * @throws Exception
     */
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        retAts.reqSeqID = p_reqBat.reqBatchNO;
        try {
            // 代收付文件内容
            StringBuilder sbFileContent = new StringBuilder();
            // 文件明细
            while (p_reqBat.readRecord()) {
                String postScript = p_reqBat.reqBatchNO + "-" + p_reqBat.readedDetail.askNumber;
                String payAmt = p_reqBat.readedDetail.payAmount;
                String certType = convertCertTypeToBank(p_reqBat.readedDetail.certType);
                String certNum = p_reqBat.readedDetail.certNum;
                //前端传值不准确，证件号码证件类型选输
                if (getBankConfig().getValueAsBool("certIsEmpty"))  {
                    certNum="";
                    certType="";
                }
                String oppAct = "";
                String oppName = "";
                if (p_reqBat.reqHeader.isBatPay) {
                    oppAct = p_reqBat.readedDetail.recAct;
                    oppName = p_reqBat.readedDetail.recName;
                } else {
                    oppAct = p_reqBat.readedDetail.payAct;
                    oppName = p_reqBat.readedDetail.payName;
                }
                // 明细信息:账号,证件号码,证件类型,姓名,金额,地址,电话,邮编,备注,类型
                String tmpReqBodyDetail = MessageFormat.format("{0},{1},{2},{3},{4},,,,{5},0\n", oppAct, certNum, certType, oppName, payAmt, postScript);
                sbFileContent.append(tmpReqBodyDetail);
            }
            WriteBankLogLn2("批次提交文件明细内容:\r\n" + sbFileContent.toString());

            // 上传文件保存本地: FP+单位编码（8位）+日期(8位)+3位顺序号
            String tmpPaySendDate = Format.Date8Format.format(getDayCutTime(p_reqBat.getPayDateTime()));
            String tmpUploadFileName = "FP" + bankFront.org + tmpPaySendDate + "001.txt";
            String tmpLocalMarkPath = getTempFileDirectory(getDayCutTime(p_reqBat.getPayDateTime())) + File.separator + tmpUploadFileName;
            String tmpUploadFiledir="FP" + bankFront.corpNo + tmpPaySendDate;
            boolean mulFiles = getBankConfig().getValueAsBool("mulFiles");
            this.WriteBankLogLn("mulFiles:"+mulFiles);
            if (mulFiles){
                String tmpLocalSavePath = getTempFileDirectory(getDayCutTime(p_reqBat.getPayDateTime()))+File.separator +"FP" + bankFront.corpNo + tmpPaySendDate;
                WriteBankLogLn2("多批次文件上传开始");
                String tmpMarkDataDir = getDataFileDirectory(getDayCutTime(p_reqBat.getPayDateTime())) + File.separator + "bat";
                String tmpLocalBatNoPath = StringHelper.trimEnd(tmpMarkDataDir, File.separator) + File.separator + p_reqBat.reqBatchNO + ".txt";
                int maxBatch = 1;
                File dataFileDir = new File(tmpMarkDataDir);
                if (dataFileDir.exists()) {
                    int len = dataFileDir.listFiles().length;
                    if (len > 1) {
                        maxBatch = len + 1;
                    } else {
                        maxBatch = 2;
                    }
                }
                //明细文件名称
                tmpUploadFileName = "FP" + bankFront.org + tmpPaySendDate + String.format("%3s", maxBatch).replace(" ", "0")+".txt";
                WriteBankLogLn2("批次号映射文件路径: " + tmpLocalBatNoPath);
                FileHelper.writeFile(tmpLocalBatNoPath, tmpUploadFileName, getCharset());
                //汇总文件名称
                String tmpUploadSumFileName = "FP" + bankFront.org + tmpPaySendDate + "TOT.txt";
                String tmpReqSum=MessageFormat.format("{0},{1},{2},{3},{4}\n", bankFront.org, tmpPaySendDate,p_reqBat.totalNum, p_reqBat.totalAmt,tmpUploadFileName);
                WriteBankLogLn2("批次提交文件写入汇总的内容为:\r\n" + tmpReqSum);
                String tmpLocalDePath = tmpLocalSavePath + File.separator + tmpUploadFileName;
                String tmpLocalSumPath = tmpLocalSavePath + File.separator + tmpUploadSumFileName;
                WriteBankLogLn2("批次文件保存本机路径: " + tmpLocalSavePath);
                //汇总文件存在修改 不存在新建
                File LocalMarkSumFile = new File(tmpLocalSumPath);
                if (LocalMarkSumFile.exists()) {
                    String Sumontent = FileHelper.readToString(
                            LocalMarkSumFile, getCharset());
                    FileHelper.writeFile(LocalMarkSumFile, Sumontent
                            + tmpReqSum, getCharset());
                } else {
                    FileHelper.writeFile(LocalMarkSumFile, tmpReqSum, getCharset());
                }
                FileHelper.appendFile(tmpLocalDePath, sbFileContent.toString(), getCharset());
                //写入汇总文件
                WriteBankLogLn("批次文件写入成功.");
                FtpReceiver ftpReceiver = sendToBank(tmpLocalDePath, tmpLocalSumPath,tmpUploadFileName,tmpUploadSumFileName, tmpUploadFiledir);
                retAts.respCode = "0";
                if (ftpReceiver.isCompleted) {
                    retAts.respInfo = "支付文件上传成功";
                    retAts.transState = "Uploaded";
                    retAts.payInfoCode = "I4001";
                } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                    retAts.respInfo = "支付文件上传失败";
                    retAts.transState = "BatchFailed";
                    retAts.payInfoCode = "E9999";
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = ftpReceiver.connMsg;
                }
            }
            else
                {
                    WriteBankLogLn2("批次文件保存本机路径: " + tmpLocalMarkPath);
                    FileHelper.appendFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset());
                    WriteBankLogLn("批次文件写入成功.");
                    retAts.respInfo = "上传成功";
                    retAts.transState = "Uploaded";
                    retAts.payInfoCode = "I4001";
                }

        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 批量代收付状态查询
     *
     * @param p_reqQryBat
     * @return
     * @throws Exception
     */
    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.reqSeqID = p_reqQryBat.reqBatchNO;
        FtpPortClient ftpPortClient = null;
        try {
            // 下载文件名命名规则:HP+单位编码（8位）+日期(8位)+3位顺序号.txt
            String dayCutTime = Format.Date8Format.format(getDayCutTime(p_reqQryBat.getBgnDateTime()));
            String tmpDownFileName = "HP" + bankFront.org + dayCutTime + "001.txt";

            if (getBankConfig().getValueAsBool("mulFiles")){
                String tmpMarkDataDir = getDataFileDirectory(getDayCutTime(p_reqQryBat.getBgnDateTime())) + File.separator + "bat";
                String tmpLocalMarkPath = StringHelper.trimEnd(tmpMarkDataDir, File.separator) + File.separator + p_reqQryBat.reqBatchNO + ".txt";
                WriteBankLogLn2("本地批次号映射文件路径: " + tmpLocalMarkPath);
                File localMarkFile = new File(tmpLocalMarkPath);
                if (!localMarkFile.exists()) {
                    retAts.respCode = "-1";
                    retAts.respInfo = "批次流水映射文件未生成，尚未回盘!";
                    retAts.writeAfterDetail();
                    return retAts;
                }
                 tmpDownFileName = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
                 tmpDownFileName=  tmpDownFileName.replace("FP","HP");

            }
            String tmpLocalMarkPath = createTempFileDirectory() + File.separator + tmpDownFileName;
            WriteBankLogLn2("批次结果文件保存本地路径: " + tmpLocalMarkPath);
            FtpSet ftpSet = bankFront.getFtpSet("bat");
            String downDir = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + "HP" + bankFront.corpNo + dayCutTime;
            String ftpDownFilePath = StringHelper.trimEnd(downDir, "/") + "/" + tmpDownFileName;
            WriteBankLogLn("结果文件FTP服务器路径:" + ftpDownFilePath);
            ftpPortClient = new FtpPortClient(ftpSet);
            FtpReceiver ftpReceiver = ftpPortClient.downloadFileFromDir(downDir, tmpDownFileName, tmpLocalMarkPath);
            if (ftpReceiver.isCompleted) {
                WriteBankLogLn("结果文件下载成功,开始解析...");
                String tmpStrRet = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
                WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrRet);
                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    retAts.respCode = "0";
                    StringReader strReader = new StringReader(tmpStrRet);
                    BufferedReader tmpReader = new BufferedReader(strReader);
                    while(true) {
                        String eachline = tmpReader.readLine();
                        if(StringHelper.isNullOrEmpty(eachline)){
                            break;
                        }
                        if (eachline.indexOf(',') > 0) {
                            // 明细记录:序列号|客户账号|交易金额(单位:分)|借贷标志|摘要|错误代码|失败原因\n
                            String[] bodyValues = eachline.split(",");
                            RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                            //卡/账号,证件号码,证件类型,姓名,金额,地址,电话,邮编,备注,类型,成功标志（成功标志为0000）,入账日期
                            String[] reqBatchNo = bodyValues[8].split("-");
                            if (reqBatchNo.length > 1 && p_reqQryBat.reqBatchNO.equals(reqBatchNo[0])) {
                                if(p_reqQryBat.reqHeader.transType.equals("1998")){
                                    tmpRetDetail.recAct = bodyValues[0];
                                    tmpRetDetail.recName = bodyValues[3];
                                } else if(p_reqQryBat.reqHeader.transType.equals("9198")){
                                    tmpRetDetail.payAct = bodyValues[0];
                                    tmpRetDetail.payName = bodyValues[3];
                                }
                                tmpRetDetail.postScript = reqBatchNo[1];
                                tmpRetDetail.payAmount = Format.DecimalAmtFormat.format(Double.parseDouble(bodyValues[4]));
                                tmpRetDetail.result = bodyValues[10];
                                tmpRetDetail.payInfoCode = bodyValues[10];

                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "银行返回明细数据格式非法!";
                        }
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "本地批次结果文件内容为空!";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "批次结果文件下载失败:" + ftpReceiver.connMsg;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (ftpPortClient != null) {
                ftpPortClient.disconnect();
            }
        }
        retAts.writeAfterDetail();
        return retAts;
    }
}